<?php
/***************************************************************************
 *
 *   Displays messages stored in the current user's Inbox and other custom 
 *   and built-in folders.
 *   
 *   Specifying 0 (or nothing) as the folderid when loading this page
 *   displays the Inbox. Any other foldierid displays the messages,
 *   if any, in that folder.
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

define("THIS_SCRIPT", "vbms");
define("NO_REGISTER_GLOBALS", true);

require_once("./includes/vbms_preinit.php");

array_push($globaltemplates, "VBMS", "vbms_inboxfolderbit",
		"vbms_inboxemptyfolderbit", "vbms_messagebit", "vbms_emptymessagebit",
		"vbms_option");
// for an unread phrase
array_push($phrasegroups, "pm");

require_once("./global.php");
require_once(DIR . "/includes/vbms_init.php");
require_once(DIR . "/includes/vbms_functions.php");
require_once(DIR . "/includes/vbms_functions_quota.php"); // for the quota bar
require_once(DIR . "/includes/functions.php"); // for page nav
require_once(DIR . "/includes/functions_online.php"); // for sanitize_perpage

$thisfolderid = intval($_GET['folderid']);

$unreadsperfolder = vbms_get_unread_per_folder();

// make the folder dropdown
unset($builtinfolderbits);
foreach ($vbms_foldertitles as $folderid => $title)
{
	$folder = compact("folderid", "title");
	if ($folder['folderid'] == $thisfolderid)
	{
		$foldertitle = $folder['title'];
	}
	$folder['unreadcount'] = $unreadsperfolder[$folder['folderid']];
	eval("\$builtinfolderbits .= \"" . fetch_template("vbms_inboxfolderbit") . "\";");
}

unset($customfolderbits);
$result = $DB_site->query("SELECT folderid, title FROM " . TABLE_PREFIX . "vbms_folder WHERE userid = " .
		$bbuserinfo['userid'] . " ORDER BY title");
$customfolders = array();
while ($folder = $DB_site->fetch_array($result))
{
	if ($folder['folderid'] == $thisfolderid)
	{
		$foldertitle = $folder['title'];
	}
	vbms_scrubhtml($folder);
	
	$folder['unreadcount'] = $unreadsperfolder[$folder['folderid']];
	
	eval("\$customfolderbits .= \"" . fetch_template("vbms_inboxfolderbit") . "\";");
	
	$customfolders[$folder['folderid']] = $folder['title'];
}

if (empty($customfolderbits))
{
	eval("\$customfolderbits = \"" . fetch_template("vbms_inboxemptyfolderbit") . "\";");
}

// get messages (pagination data first)
if (array_key_exists("perpage", $_GET))
{
	$perpage = intval($_GET['perpage']);
}
else
{
	$perpage = $bbuserinfo['vbms_useroptions'][VBMS_OPTION_INBOX_PER_PAGE];
}

$perpage = sanitize_perpage($perpage, VBMS_PERPAGE_MAX, VBMS_PERPAGE_DEFAULT);
$pagenumber = intval($_GET['pagenumber']);
if ($pagenumber <= 0)
{
	$pagenumber = 1;
}
$startat = ($pagenumber - 1) * $perpage;

$userid = $bbuserinfo['userid'];

$message = $DB_site->query_first(
		"SELECT COUNT(messageid) AS count
		FROM " . TABLE_PREFIX . "vbms_message
		WHERE folderid = $thisfolderid AND userid = $userid");
$totalmessagecount = $message['count'];

$emptysubjecttext = addslashes(VBMS_NO_SUBJECT_TEXT);
$previewcutoff = intval(VBMS_PREVIEW_CUTOFF);
$htmlpreviewtext = addslashes($vbphrase['html_preview']);
$result = $DB_site->query(
		"SELECT messageid, dateline, readflag, fromname, xpriority, format,
		LENGTH(message) AS filesize,
		IF(deletedattachmentfilenames = \"\", 0, 1) AS containsdeletedattachments,

		IF
		(
			TRIM(subject) = \"\",
			\"$emptysubjecttext\",
			subject
		) AS subject,

		SUBSTRING(message, 1, 1000) AS message

	    FROM " . TABLE_PREFIX . "vbms_message
		WHERE folderid = $thisfolderid AND userid = $userid
		ORDER BY readflag, dateline DESC, subject
		LIMIT $startat, $perpage");
$messagesarray = array();
$messagecount = 0;
$senders = array();
while ($message = $DB_site->fetch_array($result))
{
	// init
	$message['attachmentids'] = array();
	
	// pre-scrub:
	$message['from'] = vbms_convertfromname($message['fromname']);
	
	array_push($senders, $message['from']);
	
	$message['fromisonlyemail'] = (empty($message['from']->alias) or $message['from']->alias == $message['from']->actual);
	
	$message['jssubject'] = vbms_jsescape($message['subject']);
	$message['encodedemail'] = urlencode($message['from']->email);
	
	vbms_stripvbcode($message['messagepreview']);
	
	$message['fromalias'] = $message['from']->alias;
	$message['fromemail'] = $message['from']->email;
	
	// post-scrub:
	vbms_scrubhtml($message, array("from"));
	
	$preview = strip_bbcode($message['message']);
	if (strlen($preview) > VBMS_PREVIEW_CUTOFF)
	{
		$message['messagepreview'] = substr($preview, 0, VBMS_PREVIEW_CUTOFF) . "&hellip;";
	}
	else
	{
		$message['messagepreview'] = $preview;
	}
	
	$message['subject'] = fetch_word_wrapped_string($message['subject']);
	$message['messagepreview'] = fetch_word_wrapped_string($message['messagepreview']);
	
	$message['date'] = vbdate($vboptions['dateformat'], $message['dateline']);
	$message['time'] = vbdate($vboptions['timeformat'], $message['dateline']);
	
	$message['class'] = ($message['readflag'] ? "" : "inlinemod");
	
	$messagesarray[$message['messageid']] = $message;
	
	$messagecount++;
	$i++;
}

$colspan = 5;
if ($bbuserinfo['vbms_useroptions'][VBMS_OPTION_INBOX_SHOW_QUICK_LINKS])
{
	$colspan++;
}
if ($bbuserinfo['vbms_useroptions'][VBMS_OPTION_INBOX_SHOW_SIZES])
{
	$colspan++;
}

if (empty($messagesarray))
{
	eval("\$messages = \"" . fetch_template("vbms_emptymessagebit") . "\";");
	$pagenav = "";
}
else
{
	// get address book matches
	if ($bbuserinfo['vbms_useroptions'][VBMS_OPTION_INBOX_MARK_AB_ENTRIES] and
			!in_array($thisfolderid, array(VBMS_FOLDER_DRAFTS, VBMS_FOLDER_SENTMESSAGES)))
	{
		$aliases = array();
		$actuals = array();
		foreach ($senders as $sender)
		{
			$cleanedalias = strtolower(trim($sender->alias));
			$cleanedactual = strtolower(trim($sender->email));
			if ((!empty($sender->alias) and $sender->alias != $sender->actual) and
					!in_array($cleanedalias,
					array(strtolower(trim($bbuserinfo['vbms_alias'])), strtolower(trim($bbuserinfo['username'])))))
			{
				array_push($aliases, "\"" . addslashes($cleanedalias) . "\"");
			}
			if (!empty($sender->email) and $cleanedactual != strtolower(trim($bbuserinfo['vbms_alias']) . "@" . trim($vboptions['vbms_todomain'])))
			{
				array_push($actuals, "\"" . addslashes($cleanedactual) . "\"");
			}
		}
		$aliases = array_unique($aliases);
		$actuals = array_unique($actuals);
		
		$aliases = implode(", ", $aliases);
		$actuals = implode(", ", $actuals);
		$aliasclause = iif(!empty($aliases), "AND LCASE(alias) IN ($aliases)");
		
		$addressbookentries = array();
		if (!empty($actuals))
		{
			$result = $DB_site->query(
					"SELECT alias, actual
					FROM " . TABLE_PREFIX . "vbms_addressbook
					WHERE LCASE(actual) IN ($actuals)
					$aliasclause
					AND userid = " . $bbuserinfo['userid']);
			while ($addressbook = $DB_site->fetch_array($result))
			{
				array_push($addressbookentries, $addressbook);
			}
		}
		
		//vbms_debug_print_r($addressbookentries);
		
		foreach ($messagesarray as $messageid => $message)
		{
			$messagesarray[$messageid]['senderisinab'] = false;
			
			$alias = strtolower(trim($message['from']->alias));
			$actual = strtolower(trim($message['from']->email));
			
			if (!empty($alias) and !empty($actual) and $alias != $actual)
			{
				foreach ($addressbookentries as $entry)
				{
					$entryalias = strtolower(trim($entry['alias']));
					$entryactual = strtolower(trim($entry['actual']));
					
					if ($entryalias == $alias or $entryactual == $actual)
					{
						vbms_scrubhtml($entry);
						$messagesarray[$messageid]['senderisinab'] = $entry;
						break;
					}
				}
			}
		}
	}
	
	// get attachments
	$messageids = implode(", ", array_keys($messagesarray));
	$result = $DB_site->query(
			"SELECT messageid, attachmentid, filesize
			FROM " . TABLE_PREFIX . "vbms_attachment
			WHERE userid = $userid AND messageid IN ($messageids)");
	while ($attachment = $DB_site->fetch_array($result))
	{
		array_push($messagesarray[$attachment['messageid']]['attachmentids'], $attachment['attachmentid']);
		$messagesarray[$attachment['messageid']]['filesize'] += $attachment['filesize'];
	}
	
	$altflag = false;
	$messages = "";
	foreach ($messagesarray as $messageid => $message)
	{		
		$message['attachmentcount'] = sizeof($message['attachmentids']);
		$message['attachmentids'] = implode(",", $message['attachmentids']);
		
		$message['filesize'] += $message['filesize'];
		$message['filesize'] = vb_number_format($message['filesize'], 0, true);
		
		$messagesarray[$messageid] = $message; // not really necessary except for debugging
		
		$altflag = !$altflag;
		$altclass = ($altflag ? "alt1" : "alt2");
		
		eval("\$messages .= \"" . fetch_template("vbms_messagebit") . "\";");
	}
	
	$options = array
	(
		VBMS_MASS_MARK_READ => $vbphrase['mark_as_read'],
		VBMS_MASS_MARK_UNREAD => $vbphrase['mark_as_unread'],
		VBMS_MASS_DELETE => $vbphrase['delete']
	);
	
	if ($thisfolderid != VBMS_FOLDER_INBOX)
	{
		$options[VBMS_FOLDER_INBOX] = construct_phrase($vbphrase['move_to_folder_x'], $vbphrase['inbox']);
	}
	
	foreach ($customfolders as $folderid => $title)
	{
		if ($thisfolderid != $folderid)
		{
			$options[$folderid] = construct_phrase($vbphrase['move_to_folder_x'], htmlspecialchars_uni($title));
		}
	}
	
	unset($massoptions);
	foreach ($options as $value => $text)
	{
		eval("\$massoptions .= \"" . fetch_template("vbms_option") . "\";");
	}
	
	// pagination controls
	$pagenav = construct_page_nav($pagenumber, $perpage, $totalmessagecount, "vbms.php?" . $session['sessionurl'] .	"folderid=$thisfolderid");
}

$quotabar = vbms_make_quota_bar(150);

eval("print_output(\"" . fetch_template("VBMS") . "\");");
?>